import Vue from "vue";
import axios from "axios";
import router from "./router";
import Vuex from "vuex";
Vue.use(Vuex);
import store from "./store/store";

//axios.defaults.withCredentials = true
//axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
//axios.defaults.baseURL = '/api'

// http request 拦截器
axios.interceptors.request.use(
  request => {
    if (request.method.toUpperCase() === "GET") {
      request.url += "?_=" + new Date().getTime();
    }
    return request;
  },
  err => {
    return Promise.reject(err);
  }
);

//设置全局的请求次数，请求的间隙
axios.defaults.retry = 2;
axios.defaults.retryDelay = 1000;

// http response 拦截器
axios.interceptors.response.use(
  response => {
    //console.log('请求响应后');
    const res = response.data,
      code = res.error_code,
      msg = res.message;
    if (code == 0 || code == 1 || code == undefined) {
      //成功
      return res;
    } else if (code == -4) {
      console.log(msg);
      store.commit("updataLoginFlag", false);
    } else {
      console.log(msg);
    }
  },
  err => {
    // 返回状态码不为200时候的错误处理
    const code = err.response.data.error_code;
    const status = err.response.status;
    switch (status) {
      //case 500:router.push({name:'500'});break;
      case 403:
        router.push({ name: "403" });
        break;
    }
    if (code == -4) {
      //未登录
      store.commit("updataLoginFlag", false);
    }

    let config = err.config;
    if (!config || !config.retry) return Promise.reject(err);
    config.__retryCount = config.__retryCount || 0;
    if (config.__retryCount >= config.retry) {
      return Promise.reject(err);
    }
    config.__retryCount += 1;
    let backoff = new Promise(function(resolve) {
      setTimeout(function() {
        resolve();
      }, config.retryDelay || 1);
    });
    // axios重试请求
    return backoff.then(function() {
      config.baseURL = "";
      return axios(config);
    });
  }
);

Vue.prototype.$http = axios;

export default axios;
